<template>
  <div>
    <el-card>
      <page-tool>
        <div slot="after">
          <el-button type="success" icon="el-icon-edit" size="small" @click="addMenu">添加菜单</el-button>
        </div>
      </page-tool>
      <!-- 表格区域 -->
      <el-table stripe :data="menu" :tree-props="{children: 'childs'}" default-expand-all="" row-key='id'
        style="margin:20px 0">
        <el-table-column prop="title" label="标题" width="200px">
          <template slot-scope="{row}">
            <i class="el-icon-folder-opened" v-if='row.level === 1'></i>
            <i class="el-icon-document-remove" v-else-if="!row.is_point"></i>
            <i class="el-icon-view" v-else-if="row.is_point"></i>
            <span class="tableTitle">{{row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限点代码"></el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="{row}">
            <el-button type="primary" icon="el-icon-edit" circle plain @click="editMenu(row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle plain @click="delMenu(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加菜单弹出层 -->
    <el-dialog :title="menuTittle" :visible.sync='addDialogShow' @close='btnCancel'>
      <el-form label-width="250px" :model="addForm" :rules="rules" ref="addFormRef">
        <el-form-item label="权限组名称">
          <el-radio :disabled='Boolean(addForm.id)' v-model="addForm.is_point" :label="false">菜单</el-radio>
          <el-radio :disabled='Boolean(addForm.id)' v-model="addForm.is_point" :label="true">权限点</el-radio>
        </el-form-item>
        <el-form-item label='权限组名称'>
          <el-select v-model="treeData" ref='treeSelect'>
            <el-option :value='treeDataValue' style="height:100%;background-color:#fff">
              <el-tree :data="selectData" :props="defaultProps" @node-click="handleNodeClick" default-expand-all
                node-key='id' :expand-on-click-node='false' check-on-click-node ref="treeRef"></el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="addForm.code" style="width:280px"></el-input>
        </el-form-item>
        <el-form-item label="权限标题" prop="title">
          <el-input v-model="addForm.title" style="width:280px"></el-input>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="end">
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="btnOk">确认</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, remove, detail, update } from '@/api/base/menus.js'
export default {
  name: 'menus',
  data () {
    return {
      // 接口获取回来真实的原数据
      menuList: [],
      // 自己深拷贝出来用来渲染的数据
      menu: [],
      // 控制添加表单弹框
      addDialogShow: false,
      addForm: {
        is_point: false,
        pid: '',
        code: '',
        title: ''
      },
      // 树形控件默认配置
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      // 树形控件选中的值
      treeDataValue: '',
      treeData: '',
      selectData: [],
      rules: {
        code: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async getMenuList () {
      const { data: res } = await list()
      this.menuList = res
      this.selectData = [{ title: '主导航', childs: this.menuList, id: null }]
      function deepCopy (source, level) {
        if (typeof source !== 'object' || source === null) return source

        const target = Array.isArray(source) ? [] : {}
        target.level = level
        for (const k in source) {
          if (source.hasOwnProperty(k)) {
            if (k === 'points') {
              target.childs = deepCopy(source[k], level + 1)
            } else {
              target[k] = deepCopy(source[k], level + 1)
            }
          }
        }
        return target
      }
      const res2 = deepCopy(res, 0)
      this.menu = res2
    },
    // 节点被点击时的回调
    handleNodeClick (data, node) {
      if (this.addForm.is_point && node.data.pid === null) {
        this.$refs.treeSelect.blur()
        this.$refs.treeRef.setCurrentKey(this.addForm.pid || '')
        this.$message.error('当类型为权限点时，不允许在二级菜单下添加')
        return
      }
      this.treeDataValue = data.pid
      this.addForm.pid = data.id
      this.treeData = data.title
      this.$refs.treeSelect.blur()
    },
    // 添加菜单
    btnOk () {
      const node = this.$refs.treeRef.getCurrentNode()
      if (this.addForm.is_point && node.pid === null) {
        this.$refs.treeSelect.focus()
        this.$message.error('当类型为权限点时，不允许在二级菜单下添加')
        return
      }
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        try {
          if (this.addForm.id) {
            await update(this.addForm)
          } else {
            await add(this.addForm)
          }
          this.$message.success('操作成功')
          this.getMenuList()
          this.addDialogShow = false
        } catch (err) {
          this.$message.error('操作失败')
        }
      })
    },
    delMenu (row) {
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await remove(row)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getMenuList()
        } catch (err) {
          this.$message.error('删除失败！')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    btnCancel () {
      this.addForm = {
        is_point: false,
        pid: '',
        code: '',
        title: ''
      }
      this.$refs.addFormRef.resetFields()
      this.addDialogShow = false
    },
    async editMenu (row) {
      const { data: res } = await detail(row)
      console.log(res)
      this.addForm = res
      this.treeData = res.title
      this.addDialogShow = true
    },
    // 添加菜单按钮的回调
    addMenu () {
      this.treeData = '主导航'
      this.addDialogShow = true
    }
  },
  props: {},
  computed: {
    menuTittle () {
      return this.addForm.id ? '编辑菜单' : '创建菜单'
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getMenuList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
/deep/.el-icon-arrow-right {
  display: none;
}
.tableTitle {
  font-size: 14px;
  margin-left: 10px;
}
.el-select-dropdown {
  height: 300px;
}
/deep/.el-tree-node__expand-icon.expanded {
  display: none;
}
</style>
